{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python 的 SciKit-Learn 库使用（主要讲解 如何使用SciKit-Learn进行数据规范化）\n",
    "\n",
    "- SciKit-Learn 是 Python 的重要机器学习库，它帮我们封装了大量的机器学习算法，比如分类、聚类、回归、降维等。此外，它还包括了数据变换模块"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1. Min-max 规范化\n",
    "\n",
    "- 让原始数据投射到指定的空间 [min, max]，在 SciKit-Learn 里有个函数 MinMaxScaler 是专门做这个，它允许给定一个最大值与最小值，然后将原数据投射到 [min, max] 中。默认情况下 [min,max] 是 [0,1]，也就是把原始数据投放到 [0,1] 范围内。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding:utf-8\n",
    "from sklearn import preprocessing\n",
    "import numpy as np\n",
    "# 初始化数据，每一行表示一个样本，每一列表示一个特征\n",
    "x = np.array([[ 0., -3.,  1.],\n",
    "              [ 3.,  1.,  2.],\n",
    "              [ 0.,  1., -1.]])\n",
    "# 将数据进行[0,1]规范化\n",
    "min_max_scaler = preprocessing.MinMaxScaler()\n",
    "minmax_x = min_max_scaler.fit_transform(x)\n",
    "print (minmax_x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. Z-Score 规范化\n",
    "\n",
    "- 在 SciKit-Learn 库中使用 preprocessing.scale() 函数，可以直接将给定数据进行 Z-Score 规范化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn import preprocessing\n",
    "import numpy as np\n",
    "# 初始化数据\n",
    "x = np.array([[ 0., -3.,  1.],\n",
    "              [ 3.,  1.,  2.],\n",
    "              [ 0.,  1., -1.]])\n",
    "# 将数据进行Z-Score规范化\n",
    "scaled_x = preprocessing.scale(x)\n",
    "print (scaled_x)\n",
    "# 这个结果实际上就是将每行每列的值减去了平均值，再除以方差的结果。\n",
    "# 看到 Z-Score 规范化将数据集进行了规范化，数值都符合均值为 0，方差为 1 的正态分布"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. 小数定标规范化\n",
    "\n",
    "- 需要用 NumPy 库来计算小数点的位数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding:utf-8\n",
    "from sklearn import preprocessing\n",
    "import numpy as np\n",
    "# 初始化数据\n",
    "x = np.array([[ 0., -3.,  1.],\n",
    "              [ 3.,  1.,  2.],\n",
    "              [ 0.,  1., -1.]])\n",
    "# 小数定标规范化\n",
    "j = np.ceil(np.log10(np.max(abs(x))))\n",
    "scaled_x = x/(10**j)\n",
    "print (scaled_x)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
